#!/bin/bash
<<!
方式:物理备份
工具:xtrabackup
需求1:不允许有任在安装脚本，
需求2:在脚本中，不允许有任可的交互代码
需求3:在脚本中，不可的输出内容，使用日志记录
需求4:1全量,2增量，3增量，4差异，5增量，6增量，7差异
需求5:执行报错，邮件告警
!
#定义一些变量
backup_dir=/opt/mysql_backup
#记录备份是否成功
mysql_backup=/opt/mysql_backup/mysql_backup.log
#记录备份的数据类型
mysql_status=/opt/mysql_backup/mysql_status.log
db_user=root
db_passwd="Qianfeng@123"
cmd="innobackupex --user=$db_user --password=$db_passwd"
rule=(d f i i d i i )
send_email(){
    ops_user=(945225432@qq.com 19591537598@163.com 17764768157@163.com)
    echo "[$(date +"%F %T")] $1" | mail -s "数据库备份异常" ${ops_user[@]}
}
full(){
    mv $backup_dir ${backup_dir}_$(date +"%F %T") &> /dev/null
    if [ ! -d $backup_dir/full ];then
        mkdir -p $backup_dir/full
    fi
    $cmd $backup_dir/full &> /dev/null && \
    (
        echo "[$(date +"%F %T")] full备份 成功" >> $mysql_backup
        echo "[full] $backup_dir/full/`ls $backup_dir/full/ | tail -1` "   >> $mysql_status
    ) || \
    (   
        send_email "full 备份失败"
        echo "[$(date +"%F %T")] full备份 失败" >> $mysql_backup
    )
}
other(){
    if [ ! -d $backup_dir/$1 ];then
        mkdir $backup_dir/$1 -p
    fi
    $cmd --incremental $backup_dir/$1  --incremental-basedir=$2 &> /dev/null && \
    (
        echo "[$(date +"%F %T")] ${1}备份 成功" >> $mysql_backup
        echo "[$1] $backup_dir/$1/`ls $backup_dir/$1/ | tail -1` "   >> $mysql_status
    ) || \
    (
        send_email "$1 备份失败"
        echo "[$(date +"%F %T")] ${1}备份 失败" >> $mysql_backup
    )
}

case ${rule[$(date +%w)]} in
f)
    full;;
i)
    path=$(cat $mysql_status | tail -1 | awk '{print $2}')
    other intr $path 
    ;;
d)
    path=$(fgrep "[full]" $mysql_status | tail -1 | awk '{print $2}')
    other diff $path ;;
esac

